package com.xian.im.common.sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @program: tengyue
 * @description: 支付订单号生产
 * @author: xlr
 * @create: 2019-04-01 12:33
 **/
@Component
public class RedisUniqueSequenceGenerate {


    //2位交易类型（充值01，返现02，消费03，解冻04，冻结05，服务费06）+创建时间戳（精确到秒，yyyymmddhhmmss）+6位当日交易笔数（不足6位从左至右补0）；

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String SEQUENCE_NO_NUM = "sequence:no:num:six";

    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public static final String zero = "000000";

    /**
     *  生成工具类
     * @param prefix
     * @param key  redis key
     * @return
     */
    public String getSequenceNo (String prefix ,String key ){
        LocalDateTime now1 = LocalDateTime.now();
        String time = now1.format(DATE_FORMATTER);
        Long increment = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, TimeUnit.DAYS);
        String aa = zero.substring(0, 6 - increment.toString().length()) + increment;
        return prefix+time+aa;
    }

    /**
     *  生成工具类
     * @param prefix
     * @return
     */
    public String getDefaultSequenceNo (String prefix){
        return getSequenceNo(prefix,SEQUENCE_NO_NUM);
    }
}
